package com.szw.dlyk.manager;
import com.szw.dlyk.domain.Clue;
import com.szw.dlyk.domain.Customer;
import com.szw.dlyk.mapper.ClueMapper;
import com.szw.dlyk.mapper.CustomerMapper;
import com.szw.dlyk.query.CustomerQuery;
import com.szw.dlyk.util.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class CustomerManager {

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private ClueMapper clueMapper;

    @Transactional(rollbackFor = Exception.class)
    public Boolean convertCustomer(CustomerQuery customerQuery) {
        //1、验证该线索是否已经转过客户，转过了就不能再转了
        Clue clue = clueMapper.selectByPrimaryKey(customerQuery.getClueId());
        if (clue.getState() == -1) {
            throw new RuntimeException("该线索已经转过客户，不能再转了.");
        }

        //2、向客户表插入一条数据
        Customer customer = new Customer();
        //把CustomerQuery对象里面的属性数据复制到TCustomer对象里面去(复制要求：两个对象的属性名相同，属性类型要相同，这样才能复制)
        BeanUtils.copyProperties(customerQuery, customer);
        customer.setCreateTime(new Date()); //创建时间
        //登录人的id
        Integer loginUserId = JwtUtil.parseUserFromJWT(customerQuery.getToken()).getId();
        customer.setCreateBy(loginUserId); //创建人
        int insert = customerMapper.insertSelective(customer);

        //3、把线索表的数据状态改为-1（已转客户）
        Clue clue1 = new Clue();
        clue1.setId(customerQuery.getClueId());
        clue1.setState(-1);
        int update = clueMapper.updateByPrimaryKeySelective(clue1);

        return insert >= 1 && update >= 1;
    }
}
